#include "app_pool.h"
#include "log/log.h"
#include <mqueue.h>
#include <pthread.h>
#include <stdlib.h>

static char *mq_name = "/task_queue3";
static mqd_t mq_fd;
static pthread_t *thread_pool; // 线程池的指针
static int thread_num; // 线程池大小

/**
 * 线程函数
 *  不断的从任务队列中获取任务并执行
 */
void *thread_fun(void *arg)
{
    
    Task task;
    while (1)
    {
        ssize_t len = mq_receive(mq_fd, (char *)&task, sizeof(Task), NULL);
        if (len == sizeof(Task))
        {
            task.task_fun(task.arg);
        }
    }
    
}

int app_pool_init(int size)
{
    // 初始化消息（任务）队列
    struct mq_attr attr;
    attr.mq_maxmsg = 10; // 队列中的最大消息数
    attr.mq_msgsize = sizeof(Task);
    mq_fd = mq_open(mq_name, O_CREAT | O_RDWR, 0644, &attr);
    log_debug("mq_fd=%d", mq_fd);
    if (mq_fd == -1) {
        log_error("Failed to create message queue");
        return -1;
    }

    // 初始化线程池
    thread_num = size;
    thread_pool = (pthread_t *)malloc(size * sizeof(pthread_t));
    for (int i = 0; i < size; i++)
    {
        pthread_create(&thread_pool[i], NULL, thread_fun, NULL);
    }
    
    return 0;
}


void app_pool_close()
{
    // 取消结束所有线程
    for (int i = 0; i < thread_num; i++)
    {
        pthread_cancel(thread_pool[i]);
        pthread_join(thread_pool[i], NULL);
    }
    
    // 释放线程池内存
    free(thread_pool);
    // 删除消息队列
    mq_unlink(mq_name);
}

int app_pool_registerTask(int (*task_fun)(void *), void *arg)
{
    // 创建任务
    Task task = {
        .task_fun = task_fun,
        .arg = arg
    };

    // 将任务发送任务队列
    mq_send(mq_fd, (char *)&task, sizeof(Task), 0);
    
    return 0;
}